#include "drv_sht20.h"
#include "drv_iic.h"
#include "drv_systick.h"
#include "stdio.h"
sht20_val tem_hum_data;

void drv_sht20_init(void)
{
	drv_iic_init();
}
uint16_t drv_sht20_read(uint16_t cmd)
{
	uint8_t data[2];
	uint16_t ret=0;
	drv_iic_start();
	drv_iic_senddata(0x80);
	if(drv_iic_waitACK() != ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	drv_iic_senddata(cmd);
	if(drv_iic_waitACK() != ACK)
	{
		drv_iic_stop();
		return NOACK;
	}

	drv_iic_start();
	drv_iic_senddata(0x81);
	if(drv_iic_waitACK() != ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	if(cmd == 0xe3)
	{
		drv_systick_ms(85);
	}
	if(cmd == 0xe5)
	{
		drv_systick_ms(29);
	}
	data[0] = drv_iic_readdata(ACK);
	data[1] = drv_iic_readdata(NOACK);
	drv_iic_stop();
	printf("data[0]=%d data[1]=%d\r\n",data[0],data[1]);//数据处理
	ret = ((data[0]<<8) | data[1]);
	return ret;
}
uint8_t drv_sht20_reset(void)
{
	drv_iic_start();
	drv_iic_senddata(0x80);
	if(drv_iic_waitACK() !=ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	drv_iic_senddata(0xfe);//复位命令
	if(drv_iic_waitACK() != ACK)
	{
		drv_iic_stop();
		return NOACK;
	}
	drv_iic_stop();
	return 0;
}
void drv_sht20_getdata(void)
{
	uint16_t temp1=0,temp2=0;
	temp1 = drv_sht20_read(0xe3);
	tem_hum_data.tem = -46.85+175.72*((float)temp1/65536);
	printf("Temperature=%.2f\r\n",tem_hum_data.tem);
	temp2 = drv_sht20_read(0xe5);
	tem_hum_data.hum = -6 + 125 * ((float)temp2 / 65536);
	printf(" Humidity=%.2f\r\n",tem_hum_data.hum);
}

